﻿
using LmgCMS.Model;
using System;
using System.Collections.Generic;

namespace LmgCMS.Service
{
    public class HttpHelper
    {
        static IHttpContextAccessor? _httpContextAccessor { get; set; }
        /// <summary>
        /// 依赖注入
        /// </summary>
        static HttpHelper()
        {
            _httpContextAccessor = ServiceLocator.Resolve<IHttpContextAccessor>();
        }
        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="url">接口地址</param>
        /// <param name="isCache">是否缓存</param>
        /// <returns>T类型</returns>
        public static T? Get<T>(string url, bool isCache = true) where T : class
        {
            //读取缓存
            if (isCache)
            {
                var model = MemoryCacheHelper.Get<T>(url);
                if (model != null)
                {
                    return model;
                }
            }
            if (_httpContextAccessor == null)
            {
                _httpContextAccessor = ServiceLocator.Resolve<IHttpContextAccessor>();
            }
            var baseApi = $"{_httpContextAccessor?.HttpContext?.Request.Scheme}://{_httpContextAccessor?.HttpContext?.Request.Host}/api"; //获取API地址
            //获取Token
            var token = _httpContextAccessor?.HttpContext?.Request.Cookies["lmgcmstoken"];
            ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
            //如果有Token则传过去
            if (!string.IsNullOrEmpty(token))
            {
                headers.Add(new KeyValuePair<string, string>("Authorization", $"Bearer {token}"));
            }
            var jsonData = RequestHelper.GetAsync($"{baseApi}{url}", headers).Result;
            //如果请求有错则抛出异常
            if (jsonData.statusCode != 200 && jsonData.statusCode != 204 && jsonData.statusCode != 404)
            {
                throw new ApplicationException(jsonData.reBody);
            }
            var result = jsonData.reBody.ToJson<T>();
            //存入缓存
            if (isCache && result != null)
            {
                MemoryCacheHelper.Set(url, result, new TimeSpan(0, 0, 120));
            }
            return result;
        }
        /// <summary>
        /// 获取当前匹配站点信息
        /// </summary>
        public static Site GetCurrSite(string domain)
        {
            try
            {
                var model = MemoryCacheHelper.Get<Site>(domain);
                if (model != null)
                {
                    return model;
                }
                var baseApi = $"http://localhost:28720/api"; //获取API地址
                if (_httpContextAccessor == null)
                {
                    _httpContextAccessor = ServiceLocator.Resolve<IHttpContextAccessor>();
                }
                if (_httpContextAccessor?.HttpContext?.Request.Scheme != null)
                {
                    baseApi = $"{_httpContextAccessor?.HttpContext?.Request.Scheme}://{_httpContextAccessor?.HttpContext?.Request.Host}/api"; //获取API地址
                }
                var jsonData = RequestHelper.GetAsync($"{baseApi}/Site/GetCurrSite?SiteUrl={domain}").Result;
                //存入缓存
                if (jsonData != null)
                {
                    MemoryCacheHelper.Set(domain, jsonData, new TimeSpan(0, 0, 120), true);
                }
                return jsonData.ToJson<Site>();
            }
            catch (Exception)
            {
              return new Site();
            }
          
        }
    }
}
